package system;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/keyWordSearch")
public class keyWordSearch extends HttpServlet {
	private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	int type=Integer.parseInt(req.getParameter("type"));
    	
    	String keyWord=req.getParameter("keyWord");
    	
    	sqlOperation sql = new sqlOperation();
    	
    	String result="";
    	
    	if(type==1){
    		int count = sql.getCount("select COUNT(*) from single_selection where topic like '%"+keyWord+"%'");
    		String[] questionId=sql.getQuerySet("select question_id from single_selection where topic like '%"+keyWord+"%'", count);
    		result = "{\"count\":\""+count+"\""; 
    		for(int i=0;i<count;i++){
    			result+=",\"questionId"+String.valueOf(i+1)+"\":\""+questionId[i]+"\",\"topic"+String.valueOf(i+1)+"\":\""+(sql.getQuerySet("select topic from single_selection where question_id='"+questionId[i]+"'", 1))[0]+"\"";
    		}
    		result +="}";
    	}else if(type==2) {
    		int count = sql.getCount("select COUNT(*) from multiple_selection where topic like '%"+keyWord+"%'");
    		String[] questionId=sql.getQuerySet("select question_id from multiple_selection where topic like '%"+keyWord+"%'", count);
    		result = "{\"count\":\""+count+"\""; 
    		for(int i=0;i<count;i++){
    			result+=",\"questionId"+String.valueOf(i+1)+"\":\""+questionId[i]+"\",\"topic"+String.valueOf(i+1)+"\":\""+(sql.getQuerySet("select topic from multiple_selection where question_id='"+questionId[i]+"'", 1))[0]+"\"";
    		}
    		result +="}";
    	}else if(type==3) {
    		int count = sql.getCount("select COUNT(*) from subjective_topic where topic like '%"+keyWord+"%'");
    		String[] questionId=sql.getQuerySet("select question_id from subjective_topic where topic like '%"+keyWord+"%'", count);
    		result = "{\"count\":\""+count+"\""; 
    		for(int i=0;i<count;i++){
    			result+=",\"questionId"+String.valueOf(i+1)+"\":\""+questionId[i]+"\",\"topic"+String.valueOf(i+1)+"\":\""+(sql.getQuerySet("select topic from subjective_topic where question_id='"+questionId[i]+"'", 1))[0]+"\"";
    		}
    		result +="}";
    	}
    	
    	resp.setContentType("application/json;charset=UTF-8");
		PrintWriter out = resp.getWriter();		
		out.write(result); 	
    } 
}
